﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Shapes;

namespace TouchControls.MenuFlows
{
    class FlowLeft : AbstractFlow
    {
        public FlowLeft(TouchMenuPanel panel)
            : base(panel)
        {
        }

        public override Size Arrange(System.Windows.Size availableSize)
        {
            var init = base.Arrange(availableSize);
            if (Items.Count == 0) return init;

            var offsetX = ButtonRect.X - (ItemSize + Panel.Distance);
            var offsetY = ButtonRect.Y - (TotalSize / 2) + (ButtonRect.Height / 2);
            var fullRect = new Rect(0, 0, AdornmentSize.Width, AdornmentSize.Height);

            if (offsetY < 0)
            {
                offsetY = Panel.Space;
            }
            if (offsetY + TotalSize > AdornmentSize.Height)
            {
                offsetY = AdornmentSize.Height - TotalSize - Panel.Space;
            }

            for (int i = 0; i < Items.Count; i++)
            {
                var menuRect = new Rect(offsetX, offsetY + (i * (ItemSize + Panel.Space)), ItemSize, ItemSize);
                var menu = Items[i];
                menu.ButtonRect = menuRect;
                menu.Arrange(fullRect);
                var line = Panel.CurrentItem.LineCanvas.Children[i] as Line;
                SetLine(menuRect, line);
            }
            EndLines();
            Panel.CurrentItem.MenuContainer.InvalidateArrange();

            return init;
        }

        protected override void SetLine(Rect itemPos, Line line)
        {
            line.X1 = Math.Ceiling(itemPos.X + ItemSize + (0.3 * Panel.Distance) + 1);
            line.Y1 = itemPos.Y + (ItemSize / 2);
            line.X2 = itemPos.X + ItemSize;
            line.Y2 = itemPos.Y + (ItemSize / 2);
        }

        protected override void EndLines()
        {
            if (Items.Count == 0) return;

            var firstItem = Items[0];
            var lastItem = Items[Items.Count - 1];
            var line = Panel.CurrentItem.LineCanvas.Children[Items.Count] as Line;
            line.X1 = firstItem.ButtonRect.X + firstItem.ButtonRect.Width + ChildItemLineLength;
            line.Y1 = firstItem.ButtonRect.Y + (ItemSize / 2) - (Panel.LinesThickness / 2.0);
            line.X2 = lastItem.ButtonRect.X + firstItem.ButtonRect.Width + ChildItemLineLength;
            line.Y2 = lastItem.ButtonRect.Y + (ItemSize / 2) + (Panel.LinesThickness / 2.0);
            
            line = Panel.CurrentItem.LineCanvas.Children[Items.Count + 1] as Line;
            line.X1 = ButtonRect.X - ParentItemLineLength;
            line.Y1 = ButtonRect.Y + (ButtonRect.Height / 2);
            line.X2 = Math.Ceiling(ButtonRect.X) + 1;
            line.Y2 = ButtonRect.Y + (ButtonRect.Height / 2);
        }
    }
}
